﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Blazing.BusinessObjects.Cms;
using Blazing.BusinessObjects.Widgets;
using Blazing.Web.Util;
using System.Web.UI.WebControls;
using System.Reflection;

namespace Blazing.Web.Controls
{
    [Themeable(true)]
    public class WidgetRegionControl : UserControl
    {
        #region Private Variables;
        CmsManager _manager = null;
        #endregion

        #region Properties
        public CmsManager Manager
        {
            get
            {
                if (_manager == null)
                    _manager = Blazing.Util.CmsManagerHelper.FindManagerObject(Page.Controls);
                if (_manager == null)
                    throw new ApplicationException("There was no active CmsManager object found on the current page.");
                return _manager;
            }
        }

        public int RegionId { get; set; }
        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            EnsureChildControls();
        }

        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            LiteralControl literal = new LiteralControl();
            literal.ID = string.Format("PageWidgets{0}", RegionId);
            Contentpage retPage = null;

            if (Manager.PageId != null)
            {
                retPage = CmsFacade.GetPageById(Manager.PageId.Value);
            }
            else if (!string.IsNullOrEmpty(Manager.Url))
            {
                retPage = CmsFacade.GetPageByPermalink(Manager.SiteId.Value, Manager.Url);
            }

            if (retPage != null && retPage.Widgets != null && retPage.Widgets.Count > 0)
            {
                foreach (PageWidget w in retPage.Widgets)
                {
                    if (w.Region.ID == RegionId)
                    {
                        Control c = LoadControl(w.Widget.Path);

                        if (!string.IsNullOrEmpty(w.Parameters))
                            WidgetParameters.SetParameters(c, w.Parameters);

                        Controls.Add(c);

                        Literal litSpace = new Literal();
                        litSpace.Text = "<br />";

                        Controls.Add(litSpace);
                    }
                }
            }
   
        }
    }
}
